<template>
  <div class="page-container">
    <!-- 错误提示 -->
    <div v-if="errorMessage" class="alert alert-danger alert-dismissible fade show" role="alert">
      {{ errorMessage }}
      <button type="button" class="btn-close" @click="errorMessage = ''" aria-label="Close"></button>
    </div>

    <div class="d-flex justify-content-between align-items-center mb-4">
      <h2>进度更新</h2>
    </div>

    <!-- 项目选择 -->
    <div class="card mb-4">
      <div class="card-header">
        <h5 class="card-title mb-0">选择项目</h5>
      </div>
      <div class="card-body">
        <div v-if="isLoading.projects" class="text-center py-4">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
          </div>
          <p class="mt-2">加载项目数据...</p>
        </div>
        <div v-else class="row">
          <div class="col-md-6">
            <div class="mb-3">
              <label for="projectSelect" class="form-label">项目</label>
              <select class="form-select" id="projectSelect" v-model="selectedProjectId" @change="handleProjectChange">
                <option value="">-- 请选择项目 --</option>
                <option v-for="project in projects" :key="project.id" :value="project.id">
                  {{ project.name }}
                </option>
              </select>
            </div>
          </div>
          <div class="col-md-6">
            <div class="mb-3" v-if="selectedProject">
              <label class="form-label">项目阶段</label>
              <div class="d-flex align-items-center">
                <span class="badge" :class="getStatusClass(selectedProject.status)">{{ selectedProject.status }}</span>
              </div>
            </div>
            <div class="mb-3" v-if="selectedProject && isConstructionPhase(selectedProject.status)">
              <label class="form-label">当前进度</label>
              <div class="d-flex align-items-center">
                <div class="progress flex-grow-1 me-2" style="height: 10px;">
                  <div class="progress-bar" :class="getProgressClass(selectedProject.progress)" role="progressbar" :style="{ width: selectedProject.progress + '%' }"></div>
                </div>
                <span class="fw-bold">{{ selectedProject.progress }}%</span>
              </div>
            </div>
            <div v-if="!selectedProject" class="text-muted">请先选择项目</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 进度更新表单 -->
    <div class="card mb-4" :class="{ 'disabled-card': !selectedProject || isLoading.submit }">
      <div class="card-header">
        <h5 class="card-title mb-0">更新进度</h5>
      </div>
      <div class="card-body">
        <form @submit.prevent="submitProgressUpdate">
          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label for="updateDate" class="form-label">更新日期</label>
                <input type="date" class="form-control" id="updateDate" v-model="progressUpdate.update_date" :disabled="!selectedProject">
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3">
                <label for="projectStatus" class="form-label">项目阶段</label>
                <select class="form-select" id="projectStatus" v-model="progressUpdate.project_status" :disabled="!selectedProject" @change="handleProjectStatusChange">
                  <option v-for="status in projectStatusOptions" :key="status" :value="status">{{ status }}</option>
                </select>
              </div>
            </div>
          </div>

          <div class="row">
            <div class="col-md-6" v-if="selectedProject && selectedProject.total_investment">
              <div class="mb-3">
                <label for="paymentProgress" class="form-label">付款进度 ({{ progressUpdate.payment_percentage }}%)</label>
                <input type="range" class="form-range" id="paymentProgress" min="0" max="100" step="1" v-model.number="progressUpdate.payment_percentage" :disabled="!selectedProject">
                <small class="text-muted">
                  已结算金额: {{ formatCurrency(selectedProject.total_investment * progressUpdate.payment_percentage / 100) }}
                </small>
              </div>
            </div>
            <div class="col-md-6" v-if="isConstructionPhase(progressUpdate.project_status)">
              <div class="mb-3">
                <label for="newProgress" class="form-label">施工进度 ({{ progressUpdate.new_progress }}%)</label>
                <input type="range" class="form-range" id="newProgress" min="0" max="100" step="1" v-model.number="progressUpdate.new_progress" :disabled="!selectedProject">
              </div>
            </div>
          </div>

          <div class="mb-3">
            <label for="currentProgress" class="form-label">本周进度</label>
            <textarea class="form-control" id="currentProgress" rows="3" v-model="progressUpdate.current_progress" :disabled="!selectedProject"></textarea>
          </div>

          <div class="mb-3">
            <label for="nextPlan" class="form-label">下周计划</label>
            <textarea class="form-control" id="nextPlan" rows="3" v-model="progressUpdate.next_plan" :disabled="!selectedProject"></textarea>
          </div>

          <div class="mb-3">
            <label for="issues" class="form-label">矛盾问题</label>
            <textarea class="form-control" id="issues" rows="3" v-model="progressUpdate.issues" :disabled="!selectedProject"></textarea>
          </div>

          <div class="mb-3">
            <label for="solutions" class="form-label">解决方案</label>
            <textarea class="form-control" id="solutions" rows="3" v-model="progressUpdate.solutions" :disabled="!selectedProject"></textarea>
          </div>

          <!-- 里程碑添加 -->
          <div class="mb-4">
            <div class="d-flex justify-content-between align-items-center mb-2">
              <label class="form-label mb-0">添加里程碑节点</label>
              <button type="button" class="btn btn-sm btn-outline-primary" @click="addMilestone" :disabled="!selectedProject">
                添加节点
              </button>
            </div>
            <div v-if="milestones.length > 0" class="table-responsive">
              <table class="table table-sm">
                <thead>
                  <tr>
                    <th>分类</th>
                    <th>节点名称</th>
                    <th>计划日期</th>
                    <th>实际日期</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(milestone, index) in milestones" :key="index">
                    <td>
                      <select class="form-select form-select-sm" v-model="milestone.category" :disabled="!selectedProject" @change="handleMilestoneCategoryChange(milestone)">
                        <option v-for="category in milestoneCategories" :key="category" :value="category">{{ category }}</option>
                      </select>
                    </td>
                    <td>
                      <div class="input-group input-group-sm">
                        <template v-if="!milestone.is_custom">
                          <select class="form-select form-select-sm" v-model="milestone.name" :disabled="!selectedProject" @change="handleMilestoneNameChange(milestone)">
                            <option value="">-- 选择节点 --</option>
                            <option v-for="name in milestone.available_names" :key="name" :value="name">{{ name }}</option>
                          </select>
                        </template>
                        <template v-else>
                          <input type="text" class="form-control form-control-sm" v-model="milestone.name" :disabled="!selectedProject" placeholder="输入自定义节点名称">
                        </template>
                        <button class="btn btn-sm btn-outline-secondary" type="button" @click="toggleCustomMilestone(milestone)" :disabled="!selectedProject">
                          {{ milestone.is_custom ? '选择' : '自定义' }}
                        </button>
                      </div>
                    </td>
                    <td>
                      <input type="date" class="form-control form-control-sm" v-model="milestone.planned_date" :disabled="!selectedProject">
                    </td>
                    <td>
                      <input type="date" class="form-control form-control-sm" v-model="milestone.actual_date" :disabled="!selectedProject">
                    </td>
                    <td>
                      <button type="button" class="btn btn-sm btn-outline-danger" @click="removeMilestone(index)" :disabled="!selectedProject">
                        删除
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div v-else class="text-muted small">
              点击"添加节点"按钮添加里程碑节点
            </div>
          </div>

          <!-- 进度状态评价 -->
          <div class="mb-4">
            <div class="card border-light">
              <div class="card-header bg-light">
                <h6 class="mb-0">进度状态评价</h6>
              </div>
              <div class="card-body">
                <div class="mb-3">
                  <label for="phaseStatus" class="form-label">进度状态</label>
                  <select class="form-select" id="phaseStatus" v-model="progressUpdate.phase_status" :disabled="!selectedProject">
                    <option v-for="status in phaseStatusOptions" :key="status" :value="status">{{ status }}</option>
                  </select>
                </div>
                <div class="mb-3">
                  <label for="statusComment" class="form-label">状态说明</label>
                  <textarea class="form-control" id="statusComment" rows="2" v-model="progressUpdate.status_comment" :disabled="!selectedProject" placeholder="请简要说明当前进度状态的原因..."></textarea>
                </div>
              </div>
            </div>
          </div>

          <div class="d-flex justify-content-end">
            <button type="button" class="btn btn-outline-secondary me-2" @click="resetForm" :disabled="!selectedProject || isLoading.submit">重置</button>
            <button type="submit" class="btn btn-primary" :disabled="!selectedProject || isLoading.submit">
              <span v-if="isLoading.submit" class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
              {{ isLoading.submit ? '提交中...' : '提交更新' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 最近更新记录 -->
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">最近更新记录</h5>
        <div v-if="selectedProject">
          <button class="btn btn-sm btn-outline-primary" @click="loadProjectUpdates">
            查看当前项目记录
          </button>
        </div>
      </div>
      <div class="card-body">
        <div v-if="isLoading.updates" class="text-center py-4">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
          </div>
          <p class="mt-2">加载更新记录...</p>
        </div>
        <div v-else-if="recentUpdates.length > 0">
          <div class="table-responsive">
            <table class="table table-hover">
              <thead>
                <tr>
                  <th>项目名称</th>
                  <th>更新日期</th>
                  <th>项目阶段</th>
                  <th>进度</th>
                  <th>阶段状态</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="update in recentUpdates" :key="update.id">
                  <td>{{ update.project_name }}</td>
                  <td>{{ formatDate(update.update_date) }}</td>
                  <td>
                    <span class="badge" :class="getStatusClass(update.project_status || update.status)">
                      {{ update.project_status || update.status }}
                    </span>
                  </td>
                  <td>
                    <div v-if="isConstructionPhase(update.project_status || update.status)" class="progress" style="height: 8px; width: 100px;">
                      <div class="progress-bar" :class="getProgressClass(update.new_progress || update.progress)" 
                           role="progressbar" :style="{ width: (update.new_progress || update.progress) + '%' }"></div>
                    </div>
                    <small v-if="isConstructionPhase(update.project_status || update.status)">
                      {{ update.new_progress || update.progress }}%
                    </small>
                    <small v-else>-</small>
                  </td>
                  <td>
                    <span class="badge" :class="getPhaseStatusClass(update.phase_status)">{{ update.phase_status }}</span>
                    <small v-if="update.status_comment || update.notes" class="d-block text-muted mt-1" 
                           style="max-width: 150px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                      {{ update.status_comment || update.notes }}
                    </small>
                  </td>
                  <td>
                    <button class="btn btn-sm btn-outline-info me-1" @click="viewUpdateDetails(update)">
                      查看
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div v-else class="text-center py-4">
          <p class="text-muted">暂无最近更新记录</p>
        </div>
      </div>
    </div>

    <!-- 更新详情模态框 -->
    <div class="modal fade" id="updateDetailsModal" tabindex="-1" aria-labelledby="updateDetailsModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="updateDetailsModalLabel">进度更新详情</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body" v-if="selectedUpdate">
            <div class="row mb-3">
              <div class="col-md-6">
                <p><strong>项目名称：</strong> {{ selectedUpdate.project_name }}</p>
                <p><strong>更新日期：</strong> {{ formatDate(selectedUpdate.update_date) }}</p>
                <p><strong>项目阶段：</strong> 
                  <span class="badge" :class="getStatusClass(selectedUpdate.project_status || selectedUpdate.status)">
                    {{ selectedUpdate.project_status || selectedUpdate.status }}
                  </span>
                </p>
                <p><strong>阶段状态：</strong> 
                  <span class="badge" :class="getPhaseStatusClass(selectedUpdate.phase_status)">
                    {{ selectedUpdate.phase_status }}
                  </span>
                  <span v-if="selectedUpdate.status_comment || selectedUpdate.notes" class="ms-2 small text-muted">
                    ({{ selectedUpdate.status_comment || selectedUpdate.notes }})
                  </span>
                </p>
              </div>
              <div class="col-md-6">
                <p v-if="isConstructionPhase(selectedUpdate.project_status || selectedUpdate.status)">
                  <strong>进度：</strong> {{ selectedUpdate.new_progress || selectedUpdate.progress }}%
                </p>
                <p><strong>付款进度：</strong> {{ selectedUpdate.payment_percentage }}%</p>
                <p v-if="getProjectTotalInvestment(selectedUpdate.project_id)">
                  <strong>已结算金额：</strong> 
                  {{ formatCurrency(getProjectTotalInvestment(selectedUpdate.project_id) * selectedUpdate.payment_percentage / 100) }}
                </p>
              </div>
            </div>
            <hr>
            <div class="mb-3">
              <h6>本周进度</h6>
              <p>{{ selectedUpdate.current_progress || '无' }}</p>
            </div>
            <div class="mb-3">
              <h6>下周计划</h6>
              <p>{{ selectedUpdate.next_plan || '无' }}</p>
            </div>
            <div class="mb-3">
              <h6>矛盾问题</h6>
              <p>{{ selectedUpdate.issues || '无' }}</p>
            </div>
            <div class="mb-3">
              <h6>解决方案</h6>
              <p>{{ selectedUpdate.solutions || '无' }}</p>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Modal } from 'bootstrap'

// 阶段状态选项
const phaseStatusOptions = ref(['正常进行', '阶段性迟缓', '滞后', '其他'])

// 项目阶段选项
const projectStatusOptions = ref([
  '前期-方案设计',
  '前期-施工图设计及清单编制',
  '前期-清单审核',
  '发包-发包方案编制',
  '发包-发包组织实施',
  '发包-评标结果公示',
  '施工-待开工',
  '施工-在建',
  '施工-初步验收',
  '竣工-竣工验收',
  '竣工-实体移交',
  '竣工-完成结算',
  '竣工-完成决算',
  '撤项'
])

// 项目数据
const projects = ref([])
const selectedProjectId = ref('')
const isSubmitting = ref(false)

// 计算选中的项目
const selectedProject = computed(() => {
  if (!selectedProjectId.value) return null
  return projects.value.find(p => p.id === selectedProjectId.value)
})

// 进度更新表单数据
const progressUpdate = ref({
  update_date: new Date().toISOString().split('T')[0], // 当前日期，格式：YYYY-MM-DD
  project_status: '', // 对应数据库字段: status
  new_progress: 0,    // 对应数据库字段: progress
  phase_status: '正常进行',
  current_progress: '',
  next_plan: '',
  issues: '',
  solutions: '',
  payment_percentage: 0,
  status_comment: ''  // 对应数据库字段: notes
})

// 最近更新记录
const recentUpdates = ref([])
const selectedUpdate = ref(null)
let updateDetailsModal = null

// 里程碑相关数据
const milestones = ref([])
const milestoneCategories = ref(['前期', '发包', '施工', '竣工'])

// 预设的里程碑节点
const defaultMilestones = {
  '前期': ['任务书下达', '方案设计确认', '初步设计确认', '完成施工图审查', '完成清单编制', '完成清单审核', '施工图确认'],
  '发包': ['企业邀请/招标公告发布', '企业报名时间', '开标时间', '定标时间', '中标通知书发放时间', '合同签订时间', '直接委托'],
  '施工': ['质监注册时间', '施工许可证时间', '开工令时间', '初步验收时间'],
  '竣工': ['档案验收时间', '竣工验收时间', '实体移交时间', '档案移交时间', '竣工备案时间', '结算时间', '决算时间']
}

// 添加项目里程碑数据引用
const projectMilestones = ref([])

// 添加加载状态
const isLoading = ref({
  projects: false,
  updates: false,
  submit: false
})

// 添加错误消息
const errorMessage = ref('')

// 显示错误消息
const showError = (message) => {
  errorMessage.value = message
  setTimeout(() => {
    errorMessage.value = ''
  }, 5000) // 5秒后自动清除错误消息
}

// 验证表单
const validateForm = () => {
  console.log('开始验证表单数据')
  console.log('表单数据:', JSON.stringify({
    update_date: progressUpdate.value.update_date,
    project_status: progressUpdate.value.project_status,
    new_progress: progressUpdate.value.new_progress,
    phase_status: progressUpdate.value.phase_status,
    status_comment: progressUpdate.value.status_comment,
    milestones_count: milestones.value.length
  }))
  
  // 重置验证状态
  formErrors.value = {}
  
  // 验证更新日期
  if (!progressUpdate.value.update_date) {
    formErrors.value.update_date = '请选择更新日期'
    console.log('验证失败: 更新日期未填写')
  }
  
  // 验证项目阶段
  if (!progressUpdate.value.project_status) {
    formErrors.value.project_status = '请选择项目阶段'
    console.log('验证失败: 项目阶段未选择')
  }
  
  // 如果是施工阶段，验证进度百分比
  if (isConstructionPhase(progressUpdate.value.project_status)) {
    if (progressUpdate.value.new_progress < 0 || progressUpdate.value.new_progress > 100) {
      formErrors.value.new_progress = '进度百分比必须在0-100之间'
      console.log('验证失败: 进度百分比无效', progressUpdate.value.new_progress)
    }
  }
  
  // 验证进度状态
  if (!progressUpdate.value.phase_status) {
    formErrors.value.phase_status = '请选择进度状态'
    console.log('验证失败: 进度状态未选择')
  }
  
  // 验证本周进度
  if (!progressUpdate.value.current_progress) {
    formErrors.value.current_progress = '请填写本周进度'
    console.log('验证失败: 本周进度未填写')
  }
  
  // 验证付款进度百分比
  if (progressUpdate.value.payment_percentage < 0 || progressUpdate.value.payment_percentage > 100) {
    formErrors.value.payment_percentage = '付款进度百分比必须在0-100之间'
    console.log('验证失败: 付款进度百分比无效', progressUpdate.value.payment_percentage)
  }
  
  // 如果状态为非正常进行或其他，验证状态说明
  if ((progressUpdate.value.phase_status !== '正常进行' || progressUpdate.value.phase_status === '其他') && !progressUpdate.value.status_comment) {
    formErrors.value.status_comment = '请填写状态说明'
    console.log('验证失败: 非正常状态但未填写状态说明')
  }
  
  // 验证里程碑节点
  if (milestones.value.length > 0) {
    const milestoneErrors = []
    
    milestones.value.forEach((milestone, index) => {
      if (!milestone.category) {
        milestoneErrors.push(`节点 #${index+1}: 请选择分类`)
        console.log(`验证失败: 里程碑节点 #${index+1} 未选择分类`)
      }
      
      if (!milestone.name) {
        milestoneErrors.push(`节点 #${index+1}: 请选择或输入节点名称`)
        console.log(`验证失败: 里程碑节点 #${index+1} 未填写名称`)
      }
      
      if (!milestone.planned_date && !milestone.actual_date) {
        milestoneErrors.push(`节点 #${index+1}: 请填写计划日期或实际日期`)
        console.log(`验证失败: 里程碑节点 #${index+1} 未填写计划日期或实际日期`)
      }
    })
    
    if (milestoneErrors.length > 0) {
      formErrors.value.milestones = milestoneErrors
    }
  }
  
  const isValid = Object.keys(formErrors.value).length === 0
  console.log('表单验证结果:', isValid ? '通过' : '不通过')
  if (!isValid) {
    console.log('验证错误详情:', formErrors.value)
  }
  
  // 返回是否验证通过
  return isValid
}

// 存储表单错误信息
const formErrors = ref({})

// 初始化
onMounted(async () => {
  console.log('ProgressUpdate组件初始化开始')
  
  // 初始化模态框
  updateDetailsModal = new Modal(document.getElementById('updateDetailsModal'))
  console.log('模态框初始化完成')
  
  // 加载项目数据
  await loadProjects()
  console.log('项目数据加载完成，共', projects.value.length, '个项目')
  
  // 加载最近更新记录
  await loadRecentUpdates()
  console.log('最近更新记录加载完成，共', recentUpdates.value.length, '条记录')
  
  console.log('ProgressUpdate组件初始化完成')
})

// 加载项目数据
const loadProjects = async () => {
  try {
    console.log('开始加载项目数据...')
    // 显示加载指示器
    isLoading.value.projects = true
    
    // 从API获取项目数据
    console.log('调用get-projects API...')
    const response = await window.api.database.getProjects()
    
    if (response.success) {
      console.log('项目数据加载成功，数量:', response.data.length)
      projects.value = response.data
    } else {
      console.error('加载项目数据API错误:', response.error)
      projects.value = []
      showError('加载项目数据失败: ' + response.error)
    }
  } catch (error) {
    console.error('加载项目数据失败:', error)
    projects.value = []
    showError('加载项目数据失败: ' + (error.message || '未知错误'))
  } finally {
    isLoading.value.projects = false
    console.log('项目数据加载完成')
  }
}

// 加载最近更新记录
const loadRecentUpdates = async () => {
  try {
    console.log('开始加载最近更新记录...')
    // 显示加载指示器
    isLoading.value.updates = true
    
    // 从API获取更新记录
    console.log('调用get-progress-updates API...')
    const response = await window.api.database.getProgressUpdates()
    
    if (response.success) {
      console.log('更新记录加载成功，数量:', response.data.length)
      recentUpdates.value = response.data
      
      // 输出前3条记录的字段，帮助诊断字段兼容性问题
      if (response.data.length > 0) {
        console.log('更新记录第一条数据字段列表:')
        const firstRecord = response.data[0]
        Object.keys(firstRecord).forEach(key => {
          console.log(`  ${key}: ${typeof firstRecord[key]} = ${firstRecord[key]}`)
        })
      }
    } else {
      console.error('加载更新记录API错误:', response.error)
      recentUpdates.value = []
      showError('加载更新记录失败: ' + response.error)
    }
  } catch (error) {
    console.error('加载最近更新记录失败:', error)
    recentUpdates.value = []
    showError('加载更新记录失败: ' + (error.message || '未知错误'))
  } finally {
    isLoading.value.updates = false
    console.log('更新记录加载完成')
  }
}

// 加载特定项目的更新记录
const loadProjectUpdates = async () => {
  if (!selectedProjectId.value) return
  
  try {
    // 显示加载指示器或禁用相关控件
    
    // 从API获取特定项目的更新记录
    const response = await window.api.database.getProgressUpdates(selectedProjectId.value)
    
    if (response.success) {
      if (response.data.length > 0) {
        recentUpdates.value = response.data
      } else {
        // 如果没有找到记录，显示提示
        alert('该项目暂无更新记录')
        // 重新加载所有记录
        await loadRecentUpdates()
      }
    } else {
      console.error('加载项目更新记录API错误:', response.error)
      // 重新加载所有记录
      await loadRecentUpdates()
    }
  } catch (error) {
    console.error('加载项目更新记录失败:', error)
    // 重新加载所有记录
    await loadRecentUpdates()
  }
}

// 处理项目选择变化
const handleProjectChange = async () => {
  console.log('项目选择变更为:', selectedProjectId.value)
  
  if (selectedProject.value) {
    console.log('选中项目详情:', {
      id: selectedProject.value.id,
      name: selectedProject.value.name,
      status: selectedProject.value.status,
      progress: selectedProject.value.progress,
      phase_status: selectedProject.value.phase_status
    })
    
    // 重置表单并设置初始值
    resetForm()
    // 清空里程碑
    milestones.value = []
    // 加载项目里程碑
    await loadProjectMilestones(selectedProjectId.value)
  } else {
    console.log('未选择项目或选择已清空')
  }
}

// 加载项目里程碑
const loadProjectMilestones = async (projectId) => {
  try {
    console.log(`开始加载项目(ID:${projectId})的里程碑...`)
    
    // 从API获取项目里程碑
    console.log('调用get-project-milestones API...')
    const response = await window.api.database.getProjectMilestones(projectId)
    
    if (response.success && response.data.length > 0) {
      // 这里我们不直接设置milestones.value
      // 而是用于在需要时填充计划日期信息
      console.log('加载到项目里程碑数量:', response.data.length)
      
      // 存储项目里程碑数据
      projectMilestones.value = response.data
      
      // 记录第一个里程碑的详细信息
      if (response.data.length > 0) {
        console.log('第一个里程碑数据示例:', JSON.stringify(response.data[0], null, 2))
      }
    } else {
      console.log('未找到项目里程碑或API调用失败')
      if (!response.success) {
        console.error('API错误:', response.error)
      }
    }
  } catch (error) {
    console.error('加载项目里程碑失败:', error)
  } finally {
    console.log('项目里程碑加载过程完成')
  }
}

// 重置表单
const resetForm = () => {
  if (!selectedProject.value) {
    console.log('重置表单失败: 没有选择项目')
    return
  }
  
  console.log('开始重置表单...')
  const isConstruction = isConstructionPhase(selectedProject.value.status)
  
  const formData = {
    update_date: new Date().toISOString().split('T')[0],
    project_status: selectedProject.value.status,
    new_progress: isConstruction ? selectedProject.value.progress : 0,
    phase_status: selectedProject.value.phase_status,
    current_progress: '',
    next_plan: '',
    issues: '',
    solutions: '',
    payment_percentage: 0,
    status_comment: '' // 重置状态说明
  }
  
  console.log('重置表单数据:', formData)
  progressUpdate.value = formData
  console.log('表单重置完成')
}

// 更新提交进度更新函数，添加验证
const submitProgressUpdate = async () => {
  if (!selectedProject.value) return
  
  console.log('=== 开始提交进度更新 ===')
  console.log('项目ID:', selectedProjectId.value)
  console.log('项目名称:', selectedProject.value.name)
  
  // 先验证表单
  if (!validateForm()) {
    // 显示验证错误
    let errorMessage = '表单验证失败，请检查以下问题：\n'
    
    // 格式化错误信息
    for (const key in formErrors.value) {
      if (key === 'milestones') {
        errorMessage += formErrors.value[key].join('\n') + '\n'
      } else {
        errorMessage += formErrors.value[key] + '\n'
      }
    }
    
    // 显示错误信息
    showError(errorMessage)
    console.log('表单验证失败:', formErrors.value)
    return
  }
  
  try {
    isSubmitting.value = true
    isLoading.value.submit = true
    
    // 确保非施工阶段的进度为0
    if (!isConstructionPhase(progressUpdate.value.project_status)) {
      progressUpdate.value.new_progress = 0
    }
    
    // 准备提交数据
    const updateData = {
      project_id: selectedProjectId.value,
      update_date: progressUpdate.value.update_date,
      status: progressUpdate.value.project_status,
      progress: progressUpdate.value.new_progress,
      phase_status: progressUpdate.value.phase_status,
      current_progress: progressUpdate.value.current_progress,
      next_plan: progressUpdate.value.next_plan,
      issues: progressUpdate.value.issues,
      solutions: progressUpdate.value.solutions,
      payment_percentage: progressUpdate.value.payment_percentage,
      notes: progressUpdate.value.status_comment
    }
    
    // 添加里程碑数据（如果有）
    if (milestones.value.length > 0) {
      updateData.milestones = milestones.value
    }
    
    console.log('提交数据详情:', JSON.stringify(updateData, null, 2))
    
    // 提交到API
    console.log('调用submit-progress-update API...')
    const response = await window.api.database.submitProgressUpdate(updateData)
    
    console.log('API响应:', response)
    
    if (response.success) {
      console.log('进度更新提交成功, updateId:', response.updateId)
      
      // 更新项目进度和状态（以保持本地数据同步）
      const projectIndex = projects.value.findIndex(p => p.id === selectedProjectId.value)
      if (projectIndex !== -1) {
        // 更新项目阶段
        projects.value[projectIndex].status = progressUpdate.value.project_status
        
        // 只有在施工阶段才更新进度
        if (isConstructionPhase(progressUpdate.value.project_status)) {
          projects.value[projectIndex].progress = progressUpdate.value.new_progress
        }
        
        projects.value[projectIndex].phase_status = progressUpdate.value.phase_status
      }
      
      // 重置表单
      resetForm()
      // 清空里程碑
      milestones.value = []
      
      // 重新加载更新记录以显示最新数据
      await loadRecentUpdates()
      
      // 显示成功消息
      alert('进度更新成功！')
    } else {
      console.error('提交进度更新API错误:', response.error)
      alert('提交失败: ' + response.error)
    }
  } catch (error) {
    console.error('提交进度更新失败:', error)
    showError('提交失败: ' + (error.message || '未知错误'))
  } finally {
    console.log('=== 进度更新过程结束 ===')
    isSubmitting.value = false
    isLoading.value.submit = false
  }
}

// 查看更新详情
const viewUpdateDetails = (update) => {
  selectedUpdate.value = update
  updateDetailsModal.show()
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  
  // 简单格式化，可根据需要调整
  return dateString
}

// 格式化货币
const formatCurrency = (amount) => {
  if (amount === undefined || amount === null) return '¥0.00'
  
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 2
  }).format(amount)
}

// 获取进度条样式类
const getProgressClass = (progress) => {
  if (progress >= 75) return 'bg-success'
  if (progress >= 50) return 'bg-info'
  if (progress >= 25) return 'bg-warning'
  return 'bg-danger'
}

// 获取阶段状态样式类
const getPhaseStatusClass = (status) => {
  if (status === '正常进行') return 'bg-success'
  if (status === '阶段性迟缓') return 'bg-warning'
  if (status === '滞后') return 'bg-danger'
  if (status === '其他') return 'bg-info'
  return 'bg-secondary'
}

// 获取项目状态样式类
const getStatusClass = (status) => {
  if (!status) return 'bg-secondary';
  if (status.startsWith('施工-')) return 'bg-warning'
  if (status.startsWith('竣工-')) return 'bg-success'
  if (status.startsWith('前期-')) return 'bg-info'
  if (status.startsWith('发包-')) return 'bg-primary'
  if (status === '撤项') return 'bg-danger'
  return 'bg-secondary'
}

// 判断项目是否处于施工阶段
const isConstructionPhase = (status) => {
  if (!status) {
    console.log('isConstructionPhase: status为空，返回false')
    return false;
  }
  const result = status.startsWith('施工-')
  console.log(`isConstructionPhase: 检查状态 "${status}" 是否为施工阶段: ${result}`)
  return result
}

// 添加里程碑节点
const addMilestone = () => {
  // 默认选择第一个分类
  const category = milestoneCategories.value[0]
  
  milestones.value.push({
    category: category,
    name: '',
    is_custom: false, // 是否自定义节点
    planned_date: '', // 计划日期
    actual_date: new Date().toISOString().split('T')[0], // 实际日期默认为当前日期
    available_names: defaultMilestones[category] // 可选的预设节点名称
  })
}

// 移除里程碑节点
const removeMilestone = (index) => {
  milestones.value.splice(index, 1)
}

// 处理里程碑分类变化
const handleMilestoneCategoryChange = (milestone) => {
  // 更新可选的预设节点名称
  milestone.available_names = defaultMilestones[milestone.category]
  // 重置节点名称
  milestone.name = ''
  milestone.is_custom = false
  // 重置计划日期
  milestone.planned_date = ''
  // 尝试获取计划日期
  tryGetPlannedDate(milestone)
}

// 尝试获取计划日期
const tryGetPlannedDate = (milestone) => {
  if (selectedProject.value && !milestone.is_custom) {
    // 1. 先从已加载的项目里程碑中查找
    const existingMilestone = projectMilestones.value.find(
      m => m.category === milestone.category && m.name === milestone.name
    )
    
    if (existingMilestone && existingMilestone.planned_date) {
      milestone.planned_date = existingMilestone.planned_date
      return
    }
    
    // 2. 如果找不到，使用默认的预设日期（如果有的话）
    const mockPlannedDates = {
      '任务书下达': '2025-01-15',
      '开工令时间': '2025-02-20',
      '竣工验收时间': '2025-12-31'
    }
    
    if (mockPlannedDates[milestone.name]) {
      milestone.planned_date = mockPlannedDates[milestone.name]
    }
  }
}

// 获取项目状态
const getProjectStatus = (projectId) => {
  const project = projects.value.find(p => p.id === projectId)
  return project ? project.status : ''
}

// 获取项目总投资
const getProjectTotalInvestment = (projectId) => {
  const project = projects.value.find(p => p.id === projectId)
  return project ? project.total_investment : 0
}

// 处理项目阶段变化
const handleProjectStatusChange = () => {
  console.log('项目阶段变更为:', progressUpdate.value.project_status)
  
  // 根据选择的项目阶段调整表单
  if (isConstructionPhase(progressUpdate.value.project_status)) {
    // 如果是施工阶段，设置进度为当前项目进度或0
    const newProgress = selectedProject.value ? selectedProject.value.progress : 0
    console.log('施工阶段，设置进度为:', newProgress)
    progressUpdate.value.new_progress = newProgress
  } else {
    // 如果不是施工阶段，进度设为0
    console.log('非施工阶段，设置进度为: 0')
    progressUpdate.value.new_progress = 0
  }
}

// 处理里程碑节点名称变化
const handleMilestoneNameChange = (milestone) => {
  // 如果选择了预设节点，尝试获取计划日期
  if (!milestone.is_custom) {
    tryGetPlannedDate(milestone)
  }
}

// 切换自定义节点模式
const toggleCustomMilestone = (milestone) => {
  milestone.is_custom = !milestone.is_custom
  milestone.name = ''
  milestone.planned_date = ''
}
</script>

<style scoped>
.disabled-card {
  opacity: 0.7;
  pointer-events: none;
}

.badge {
  padding: 0.5em 0.75em;
}

.bg-success {
  background-color: #28a745 !important;
}

.bg-warning {
  background-color: #ffc107 !important;
  color: #212529 !important;
}

.bg-danger {
  background-color: #dc3545 !important;
}

.bg-info {
  background-color: #17a2b8 !important;
}

.bg-secondary {
  background-color: #6c757d !important;
}

.card {
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  margin-bottom: 1.5rem;
}

.table th, .table td {
  vertical-align: middle;
  padding: 0.75rem 1rem;
}

.form-label {
  font-weight: 500;
}

.form-range {
  height: 1.5rem;
}

.form-control:disabled, .form-select:disabled {
  background-color: #f8f9fa;
  opacity: 0.8;
}

.modal-body p {
  margin-bottom: 0.5rem;
}

.modal-body h6 {
  font-weight: 600;
  margin-bottom: 0.5rem;
}
</style>